package io.fredia.common.web;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import io.fredia.common.web.util.SpringContextHolder;
import io.fredia.common.web.util.model.ChuanglanSmsModel;


public class HttpSender {
	/* 实例化spring托管 ChuanglanSmsModel */
	private static ChuanglanSmsModel chuanglanSmsModel = SpringContextHolder.getBean(ChuanglanSmsModel.class);

	/**
	 * 短信发送 支持批量发送
	 * 
	 * @param phone
	 *            手机号码，多个号码使用","分割
	 * @param msg
	 *            短信内容
	 * @param rd
	 *            是否需要状态报告，需要1，不需要0 默认0
	 * @param ex
	 *            扩展码，非必填 无则不填
	 * @return
	 * @throws Exception
	 * @author : fredia
	 * @since : 2017年2月17日
	 */
	public static String batchSend(String phone, String msg, String report, String ex) throws Exception {
		URL url = new URL(chuanglanSmsModel.getUrl()+"send");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");
		connection.setConnectTimeout(10 * 1000);
		connection.setDoOutput(true);
		connection.connect();
		// post数据
		Map<String, String> params = new HashMap<String, String>();
		params.put("un", chuanglanSmsModel.getUsername());// 用户名
		params.put("pw", chuanglanSmsModel.getPassword());// 密码
		params.put("phone", phone);// 手机
		params.put("rd", report != null ? report : chuanglanSmsModel.getReportStatus()); // 是否回调状态
		params.put("msg", chuanglanSmsModel.getSign() + msg);// 发送内容 签名+消息内容
		params.put("ex", ex);// 扩展码
		String requestData = parseParams(params);
		if (StringUtils.isNotBlank(requestData)) {
			OutputStream outputStream = connection.getOutputStream();
			outputStream.write(requestData.getBytes("UTF-8"));
			outputStream.close();
		}
		// 获取返回结果
		if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
			InputStream in = connection.getInputStream();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
			return URLDecoder.decode(baos.toString(), "UTF-8");
		} else {
			InputStream in = connection.getErrorStream();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
			return URLDecoder.decode(baos.toString(), "UTF-8");
		}
	}

	/**
	 * 将map转为字符串
	 *
	 * @param params
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private static String parseParams(Map<String, String> params) throws UnsupportedEncodingException {
		StringBuilder stringBuilder = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			stringBuilder.append(URLEncoder.encode(entry.getKey(), "utf-8"));
			stringBuilder.append("=");
			stringBuilder.append(URLEncoder.encode(entry.getValue() == null ? "" : entry.getValue(), "utf-8"));
			stringBuilder.append("&");
		}
		String str = stringBuilder.toString();
		if (str.length() > 0) {
			str = str.substring(0, str.length() - 1);
		}
		return str;
	}
	/**
	 * 
	 * @param url
	 *            应用地址，类似于http://ip:port/msg/
	 * @param un
	 *            账号
	 * @param pw
	 *            密码
	 * @param phone
	 *            手机号码，多个号码使用","分割
	 * @param msg
	 *            短信内容
	 * @param rd
	 *            是否需要状态报告，需要1，不需要0
	 * @param ex
	 * @return 返回值定义参见HTTP协议文档
	 * @throws Exception
	 * @author : fredia
	 * @since : 2017年2月17日
	 */
	/*
	 * public static String batchSend(String url, String un, String pw, String
	 * phone, String msg, String rd, String ex) throws Exception { HttpClient
	 * client = new HttpClient(new HttpClientParams(), new
	 * SimpleHttpConnectionManager(true)); GetMethod method = new GetMethod();
	 * try { URI base = new URI(url, false); method.setURI(new URI(base, "send",
	 * false)); method.setQueryString(new NameValuePair[] { new
	 * NameValuePair("un", un), new NameValuePair("pw", pw), new
	 * NameValuePair("phone", phone), new NameValuePair("rd", rd), new
	 * NameValuePair("msg", msg), new NameValuePair("ex", ex), }); int result =
	 * client.executeMethod(method); if (result == HttpStatus.SC_OK) {
	 * InputStream in = method.getResponseBodyAsStream(); ByteArrayOutputStream
	 * baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int
	 * len = 0; while ((len = in.read(buffer)) != -1) { baos.write(buffer, 0,
	 * len); } return URLDecoder.decode(baos.toString(), "UTF-8"); } else {
	 * throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":"
	 * + method.getStatusText()); } } finally { method.releaseConnection(); } }
	 */
}
